package com.tools.security.context;

import com.sun.istack.Nullable;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SecurityContextHolder {
    private final static ThreadLocal<SecurityContext> holder = new ThreadLocal<>();

    private SecurityContextHolder() {
    }

    @NonNull
    public static SecurityContext getContext() {
        SecurityContext context = holder.get();
        if (context == null) {
            context = createEmptyContext();
            holder.set(context);
        }
        if (log.isDebugEnabled()) {
            log.debug("线程-[ {} ] -获取获取用户信息 [ {} ]", Thread.currentThread().getName(), holder.get());
        }
        return context;
    }

    public static void setContext(@Nullable SecurityContext context) {
        if (log.isDebugEnabled()) {
            log.debug("用户信息 [ {} ]存储在线程-{}", context, Thread.currentThread().getName());
        }
        holder.set(context);
    }

    public static void clearContext() {
        holder.remove();
    }

    @NonNull
    private static SecurityContext createEmptyContext() {
        return new SecurityContext(null);
    }
}
